import React, { useEffect, useState } from "react";
import { Affix, Button, Alert, Radio, Select, Input, Space, Row, Col, Table, Popover } from "antd";
import request, { exportFile } from "@/utils/request";
import { CmdbContent, CmdbHeader, isAuthorized, HcpTableTooltip, BusinessBtn } from "@/components";
import moment from "moment";
import cmdbres from "@/data/cmdbres";
import hcpUtils from "@/utils/hcpUtils";
import mockData from './mock.json';
// import "./index.less"

const ClusterTemplateInstance = ({ history, match, location, setTemplateId }) => {
    const [searchValue, setSearchValue] = useState('');
    const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [row, setRow] = useState({});
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    
    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.querySetTemplate,
                data: {
                    bizId: biz.cm_unid,
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total, 
                }));
                res.data.map((item, index) => item.key=index);
                setTableData(res.data);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        } 
    };

    useEffect(() => {
        getTableData();  
    }, []);

    const handleTableChange = (e) => {
        getTableData(e);
    };
    
    const columns = [
        {
            title: "集群名称",
            key: "bk_set_name",
            dataIndex: "bk_set_name",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "主机数量",
            key: "host_count",
            dataIndex: "host_count",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "状态",
            key: "need_sync",
            dataIndex: "need_sync",
            isShow: true,
            width: 100,
            copyable: true,
            ellipsis: true,
            render: (text, record, index) => {
                return (
                    <span>
                        <span style={{color: text ? "#3a84ff": "#2dcb56", marginRight: 5}}>●</span>
                        {text ? "待同步": "已同步"}
                    </span>
                )
            }
        },
        {
            title: "上次同步时间",
            key: "last_time",
            dataIndex: "last_time",
            isShow: true,
            width: 100,
            copyable: true,
            ellipsis: true,
            render: (text, record, index) => hcpUtils.timeConversion(text, 'YYYY-MM-DD HH:mm:ss')
        },
        {
            title: "同步人",
            key: "creator",
            dataIndex: "creator",
            isShow: true,
            width: 140,
        },
        {
            title: "操作",
            fixed: 'right',
            width: 100,
            render: (text, record, index) => {
                return (
                <Space key={record.bk_set_id}>
                    <Popover content="去同步">
                        <span 
                            disabled={!record.need_sync}
                            className="iconfont icon-synchro" 
                            onClick={() => {
                                if(record.need_sync)
                                history.push({ 
                                    pathname:  `/business/clusterTemplate/detail/${setTemplateId}/sync`, 
                                    state: {setIds: [record.bk_set_id], setTemplateId}}
                                )}}
                        />
                    </Popover>
                </Space>
                )
            }
        } 
    ]

    const onSelectRow = (record, selected, selectedRows, nativeEvent) => {
        // console.log('onSelectRow', selected, selectedRows);
        setSelectedRowKeys((keys) => {
            keys = keys || [];
            const _index = keys.findIndex((item) => item === record.bk_set_id);
            if (selected && _index == -1) {
                keys.push(record.bk_set_id);
                return [...keys];
            }
            if (!selected && _index > -1) {
                keys.splice(_index, 1);
                return [...keys];
            }
        });
    };

    const onSelectAll = (selected, selectedRows, changeRows) => {
        let idArr = tableData.map(i => i.bk_set_id);
        setSelectedRowKeys((keys) => {
            keys = keys || [];
            if (selected) {
                let keys_ = Array.from(new Set([...keys, ...idArr]));
                if (keys_.length > 10) {
                    keys_ = keys_.slice(0, 10);
                }
                return keys_;
            } else {
                let newArr = keys.filter((item) => idArr.indexOf(item) == -1);
                return newArr;
            }
        });
    };

    return (
        <section className="hcp__page">
            <section className="hcp__page__container">    
            <div style={{backgroundColor: "#fff", padding: "10px"}}>  
                <div className="affix-header">
                    <Row style={{marginBottom: 10}}>
                    <Col span={8}>
                        <Space>
                            <Button 
                                className="hcp_toolbar_btn" 
                                type="primary"
                                disabled={selectedRowKeys?.length == 0}
                                onClick={() => {
                                    history.push({ pathname:`/business/clusterTemplate/detail/${setTemplateId}/sync`,
                                     state: {setIds: selectedRowKeys, setTemplateId}})
                                }}
                            >
                                批量同步
                            </Button>
                            <Button type="primary" onClick={() => {getTableData()}} >
                                刷新
                            </Button>
                        </Space>
                    </Col>
                    <Col span={16} style={{ textAlign: "right" }}>
                        <Space>
                            <Input.Search
                                placeholder="请输入实例名称"
                                value={searchValue}
                                onChange={(e) => {
                                    setSearchValue(e.target.value);
                                }}
                                onSearch={getTableData}
                                style={{ width: "210px" }}
                                enterButton
                            />
                        </Space>
                    </Col>
                    </Row>
                </div>
                <Table
                    rowSelection={{
                        onSelect: ( record, selected, selectedRows, nativeEvent ) => onSelectRow( record, selected, selectedRows, nativeEvent ),
                        onSelectAll: (selected, selectedRows, changeRows) => onSelectAll(selected, selectedRows, changeRows),
                        selectedRowKeys,
                        getCheckboxProps: (record) => {
                            // if (!record.need_sync) {
                            //     return { disabled: true };
                            // } else {
                            //     return { disabled: false };
                            // }
                        },
                    }}
                    columns={columns}
                    loading={loading}
                    dataSource={tableData}
                    scroll={{ x: '100%' }}
                    pagination={{
                        showSizeChanger: true,
                        showQuickJumper: {
                        goButton: (
                            <Button style={{ margin: "0 10px" }}>确定</Button>
                        ),
                        },
                        ...pagination,
                    }}
                    onChange={handleTableChange}
                    hideSetting
                />
            </div>
            </section>
        </section>
    );
};

export default ClusterTemplateInstance;